<template>
  <view class="report-container">
    <!-- 睡眠信息模块 -->
    <view class="sleep-module animated fadeIn">
      <view class="module-header">
        <text class="module-date">{{ startDate }}</text>
        <text class="module-sleep-duration">{{ sleepDuration }}</text>
      </view>
      <!-- 添加分割线 -->
      <view class="divider"></view>
      <view class="sleep-content">
        <view class="sleep-score-container">
           <!-- 使用新的 Canvas 组件 -->
          <l-echart  
            ref="scoreRef" 
          ></l-echart>
        </view>
        <view class="sleep-time-container">
          <view class="sleep-time-item">
            <text class="time-label">上床时间</text>
            <text class="time-value">{{ bedtime }}</text>
          </view>
          <view class="sleep-time-item">
            <text class="time-label">起床时间</text>
            <text class="time-value">{{ wakeupTime }}</text>
          </view>
        </view>
      </view>
    </view>
    <!-- 新增一层 view 作为新模块 -->
    <view class="sleep-details-module animated fadeIn">
      <view class="module-header">
        <text class="module-title">睡眠评价</text>
      </view>
      <!-- 修改这部分代码 -->
      <text class="sleep-suggestion">{{ sleepSuggestion }}</text>
    </view>
    <!-- 分期结果模块 -->
    <view class="step-module animated fadeIn">
      <view class="module-header">
        <text class="module-title">分期结果</text>
      </view>
      <text class="sleep-info">收集脑电信号，为您进行精准的睡眠分期</text>
      <!-- 直接插入 SleepGraph 组件的模板内容 -->
      <view class="sleep-graph-container">
        <view :style="{ width: '100%' , height:'800rpx' }">
          <l-echart   
            custom-style="background-color:aliceblue; width: 100%; height: 90%;" 
            ref="chartRef"  
          ></l-echart>
          
          <view
            class="customTooltips"  
            :style="{  left: position[0] + 'px', top: position[1] + 'px', backgroundColor: 'rgba(240, 248, 255, 0.7)' }"
            v-if="params.length && position.length && showTip"
          >
            <view class="tip-content" >
              <text>序号id </text>
              <text>{{  params[0]['dataIndex']  }}</text>
            </view>
            <view class="tip-content">
              <text>时间</text>
              <text>{{ params[0]['name']  }}</text>
            </view>
            <view v-for="item in params" :key="item.seriesName">
              <view class="tip-content">
                <template v-if="!item.color.colorStops">
                  <view class="tip-color" :style="{ backgroundColor: item.color }"></view>
                  <text style="margin-right: 20rpx;">{{ item.seriesName }} </text>
                  <text>{{ item.value }} </text>
                </template>
                <template v-else>
                  <view class="tip-color" :style="{ backgroundColor: item.color.colorStops[0].color }"></view>
                  <text style="margin-right: 20rpx;">{{ item.seriesName }}</text>
                  <text>{{ getSleepStageLabel(item.value) }}</text>
                </template>
              </view>
            </view>
          </view>
          <view class="chart-section"  style="margin: auto; width: 90%;">
            <view class="legend-item">
              <view class="legend-color n1-sleep"></view>
              <text class="legend-text">N1浅睡一期</text>
            </view>
            <view class="legend-item">
              <view class="legend-color n2-sleep"></view>
              <text class="legend-text">N2浅睡二期</text>
            </view>
            <view class="legend-item">
              <view class="legend-color n3-sleep"></view>
              <text class="legend-text">N3深睡期</text>
            </view>
            <view class="legend-item">
              <view class="legend-color rem-sleep"></view>
              <text class="legend-text">REM快速眼动期</text>
            </view>
            <view class="legend-item">
              <view class="legend-color awake"></view>
              <text class="legend-text">W觉醒期</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref ,computed,onMounted} from 'vue';
/// @ts-nocheck
import * as echarts from 'echarts'
import { onLoad } from '@dcloudio/uni-app';
import { getSleepReportInfo } from '@/api/sleepReport'; // 引入接口请求方法

// 定义响应式数据
const startDate = ref<string>('');
const endDate = ref<string>('');
const sleepScore = ref<number>(0);
const bedtime = ref<string>('');
const wakeupTime = ref<string>('');


// 计算睡眠时长
const sleepDuration = computed(() => {
  const [bedHour, bedMinute] = bedtime.value.split(':').map(Number);
  const [wakeHour, wakeMinute] = wakeupTime.value.split(':').map(Number);

  let totalMinutes = (wakeHour * 60 + wakeMinute) - (bedHour * 60 + bedMinute);
  if (totalMinutes < 0) {
    totalMinutes += 24 * 60; // 处理跨天情况
  }

  const hours = Math.floor(totalMinutes / 60);
  const minutes = totalMinutes % 60;

  return `${hours}小时${minutes}分钟`;
});

// 计算属性
const sleepSuggestion = computed(() => {
  if (sleepScore.value < 40) {
    return '       您睡眠质量糟糕，建议你调整作息时间，避免睡前使用电子设备，创造一个安静舒适的睡眠环境。';
  } else if (sleepScore.value >= 40 && sleepScore.value < 80) {
    return '       您睡眠质量良好，可以尝试在睡前进行一些放松的活动，如冥想或阅读，以提高睡眠质量。';
  } else {
    return '       您睡眠质量高效，请继续保持良好的作息习惯！';
  }
});

const scoreOption = {
  series: [
    {
      type: 'gauge',
      startAngle: 180,
      endAngle: 0,
      center: ['50%', '70%'],
      radius: '90%',
      min: 0,
      max: 100,
      splitNumber: 10,
      axisLine: {
        lineStyle: {
          width: 4,
          color: [
            [0.4, '#FF6E76'],
            [0.8, '#FDDD60'],
            [1, '#7CFFB2']
          ]
        }
      },
      pointer: {
        icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
        length: '12%',
        width: 20,
        offsetCenter: [0, '-50%'],
        itemStyle: {
          color: 'auto'
        }
      },
      axisTick: {
        length: 12,
        lineStyle: {
          color: 'auto',
          width: 2
        }
      },
      splitLine: {
        length: 20,
        lineStyle: {
          color: 'auto',
          width: 5
        }
      },
      axisLabel: {
        color: '#464646',
        fontSize: 15,
        distance: -40,
        rotate: 'tangential',
        formatter: function (value: number) {
          if (value===20) {
            return '糟糕';
          } else if ( value === 60) {
            return '良好';
          } else if (value === 90) {
            return '高效';
          }
          return '';
        }
      },
      title: {
        offsetCenter: [0, '25%'],
        fontSize: 30,
		 color: '#777777',
      },
      detail: {
        fontSize: 50,
        offsetCenter: [0, '-15%'],
        valueAnimation: true,
        formatter: function (value: number) {
          return Math.round(value) + '';
        },
        color: 'inherit'
      },
      data: [  ]
    }
  ]
};

//得分环代码
const scoreRef = ref(null);

const initscore = async () => {
  if(scoreRef.value== null) return;
  generateScoreSeriesData();
  const gauge = await scoreRef.value!.init(echarts, null)
  gauge.setOption(scoreOption)
}

const formatTime = (date: Date) => {
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${hours}:${minutes}:${seconds}`;
};

const formatTime2 = (date: Date) => {
  // 去掉 padStart 方法，不补零
  const month = String(date.getMonth() + 1);
  const day = String(date.getDate());
  return `${month}月${day}日`;
};


const formatTime3 = (date: Date) => {
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${hours}:${minutes}`;
};

const xAxis = ref([
    {
      type: 'category',
      boundaryGap: true,
      data: (function (){
        let now = new Date();
        let res = [];
    
        let len = 1000;
        while (len--) {
          res.unshift(formatTime(now).replace(/^\D*/,''));
          now = new Date(now.getTime() - 2000);
        
      }
        return res;
      })()
    },
    {
      type: 'category',
      boundaryGap: true,
      data: (function (){
        let res = [];
        
          let len = 1000;
          while (len--) {
            res.push(1000 - len - 1);
          }
        
        
        return res;
      })()
    }
  ]);

const getSleepStageLabel = (value: number) => {
  if (value > 100 && value <= 200) {
    return 'N1';
  } else if (value > 200 && value <= 400) {
    return 'N2';
  } else if (value > 400 && value <= 600) {
    return 'N3';
  } else if (value > 600 && value <= 800) {
    return 'REM';
  } else if (value > 800 && value <= 1000) {
    return 'W';
  }
  return '';
};

const yAxis = ref([
  {
    type: 'value',
    scale: true,
    name: '分期结果',
    max: 1200,
    min: 0,
    axisLabel: {
      formatter: getSleepStageLabel
    }
  }
]);

const barValues = [ 
  {
    value: 200,
    showBackground: true,
    itemStyle: {
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#83bff6' },
        { offset: 0.5, color: '#188df0' },
        { offset: 1, color: '#188df0' }
      ])
    },
    emphasis: {
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#2378f7' },
          { offset: 0.7, color: '#2378f7' },
          { offset: 1, color: '#83bff6' }
        ])
      }
    }
  },
  {
    value: 400,
    showBackground: true,
    itemStyle: {
      // 使用青绿色渐变
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#00FFCC' },
        { offset: 0.5, color: '#00CC99' },
        { offset: 1, color: '#00CC99' }
      ])
    },
    emphasis: {
      itemStyle: {
        // 青绿色强调色渐变
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#009973' },
          { offset: 0.7, color: '#009973' },
          { offset: 1, color: '#00FFCC' }
        ])
      }
    }
  },
  {
    value: 600,
    showBackground: true,
    itemStyle: {
      // 使用新的颜色，这里选择绿色
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#32CD32' },
        { offset: 0.5, color: '#228B22' },
        { offset: 1, color: '#228B22' }
      ])
    },
    emphasis: {
      itemStyle: {
        // 使用淡绿色强调颜色
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#90EE90' }, // 淡绿色起始色
          { offset: 0.7, color: '#90EE90' }, // 淡绿色中间色
          { offset: 1, color: '#32CD32' } // 与原颜色衔接
        ])
      }
    }
  },
  {
    value: 800,
    showBackground: true,
    itemStyle: {
      // 使用黄色
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#FFFF00' },
        { offset: 0.5, color: '#FFD700' },
        { offset: 1, color: '#FFD700' }
      ])
    },
    emphasis: {
      itemStyle: {
        // 淡黄色强调色渐变
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#FFFF00' }, // 淡黄色起始色
          { offset: 0.7, color: '#FFD700' }, // 淡黄色中间色
          { offset: 1, color: '#FFFF00' } // 与原颜色衔接
        ])
      }
    }
  },
  {
    value: 1000,
    showBackground: true,
    itemStyle: {
      // 使用红色
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#FF0000' }, // 红色起始色
        { offset: 0.5, color: '#CC0000' }, // 红色中间色
        { offset: 1, color: '#CC0000' } // 红色结束色
      ])
    },
    emphasis: {
      itemStyle: {
        // 淡红色强调色渐变
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#FF6666' }, // 淡红色强调起始色
          { offset: 0.7, color: '#FF6666' }, // 淡红色强调中间色
          { offset: 1, color: '#FF0000' } // 淡红色强调结束色
        ])
      }
    }
  }
];

const series = ref([
  {
    name: '睡眠分期',
    type: 'bar',
    data: [] // 初始为空，等待子组件挂载完成后再填充数据
  }
]);
const generateScoreSeriesData = () => {
  scoreOption.series[0].data[0]={
          value: sleepScore.value,
          name: '睡眠得分'
        }
}


const generateSeriesData = () => {
  const res = [];
  let len = 1000;
  while (len--) {
    const randomIndex = Math.floor(Math.random() * barValues.length);
    res.push(barValues[randomIndex]);
  }
  series.value[0].data = res;
};

const option = {
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#283b56'
      }
    },
    renderMode: 'richText',
    position: (point, paras, dom, rect, size) => {
      // 假设自定义的tooltips尺寸
	  if(!showTip.value){
      const box = [170, 170]
      // 偏移
      const offsetX = point[0] < size.viewSize[0] / 2 ? 20 : -box[0] - 20
      const offsetY = point[1] < size.viewSize[1] / 2 ? 20 : -box[1] - 20
      const x = point[0] + offsetX
      const y = point[1] + offsetY
      position.value = [x, y]
	  }
      params.value = paras
    },
    formatter: (params, ticket, callback) => {},
  },
  legend: {
    data: ['睡眠分期']
  },
  xAxis: xAxis.value,
  yAxis: yAxis.value,
   dataZoom: 
  [
      {
        type: 'slider',
        show: true,
        xAxisIndex: [0,1],
        startValue: 0,
        endValue: 50
      },
      {
        type: 'inside',
        xAxisIndex: [0,1],
        startValue: 0,
        endValue: 50
      }
    ],
  series: series.value
};


let chart = null;
const chartRef = ref(null);
const showTip = ref(false);
const position = ref([0, 0]);
const params = ref([]);

const init = async () => {
  if(chartRef.value== null) return;
  generateSeriesData();
   chart = await chartRef.value!.init(echarts, null)
  chart.setOption(option)
  // 监听tooltip显示事件
  chart.on('showTip', (params) => {
    showTip.value = true

  })
  chart.on('hideTip', (params) => {
    setTimeout(() => {
      showTip.value = false
    }, 300)
  })
  let zoomSize = 6;
	chart.on('click', function (params) {
		let dataAxis=option.xAxis[0].data;
    console.log(Math.max(params.dataIndex - zoomSize , 0))
    console.log(Math.min(params.dataIndex + zoomSize , option.series[0].data.length - 1))
		// chart.dispatchAction({
		// 	type: 'dataZoom',
		// 	startValue: dataAxis[Math.max(params.dataIndex - zoomSize , 0)],
		// 	endValue: dataAxis[Math.min(params.dataIndex + zoomSize , option.series[0].data.length - 1)]
		// });
	})
}


// 获取睡眠报告信息
const fetchReportInfo = async (reportId: number) => {
  try {
    const response = await getSleepReportInfo(reportId);
    const reportData = response.data;
    startDate.value = formatTime2(new Date(reportData.startTime));
    endDate.value = formatTime2(new Date(reportData.endTime));
    //  @ts-ignore
    sleepScore.value = reportData.sleepQuality;
    bedtime.value = formatTime3(new Date(reportData.startTime));
    wakeupTime.value = formatTime3(new Date(reportData.endTime));
  } catch (error) {
    console.error('获取睡眠报告信息失败:', error);
  }
};

// 从 URL 参数中获取 reportId
onLoad((options: any) => {

  const reportId = parseInt(options.id);
  if (reportId) {
    fetchReportInfo(reportId);
  }
});

// 挂载时调用方法
onMounted(() => {
   // 组件能被调用必须是组件的节点已经被渲染到页面上
   setTimeout(async()=>{
    await init();
    await initscore();
    },300)
});
</script>

<style lang="scss" scoped>
.report-container {
  padding: 20rpx;
  color: black; 
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  background-color: #b6c6bf; 
}

.module-header {
  display: flex;
  // 修改字体大小
  font-size: 40rpx; 
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.module-title {
  // 修改字体大小
  font-size: 40rpx; 
  
  font-weight: bold;
  color: black; 
}

.sleep-info {
  // 修改字体大小
  font-size: 30rpx; 
  margin-bottom: 10rpx;
  // 修改颜色为半透明黑色，降低透明度
  color: rgba(0, 0, 0, 0.5); 
}

.sleep-point {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.sleep-icon {
  width: 60rpx;
  height: 60rpx;
}

.sleep-level {
  // 修改字体大小
  font-size: 18rpx; 
  margin-top: 5rpx;
  color: black; 
}

.sleep-suggestion {
  // 修改字体大小
  font-size: 30rpx; 
  margin-bottom: 10rpx;
  color: rgba(0, 0, 0, 0.5); 
  line-height: 1.5 !important; 
  white-space: pre-wrap !important;
  word-wrap: break-word !important; 
  text-indent: 2em !important; 
}

.sleep-module {
  margin-top: 0; 
  // 为睡眠信息模块添加背景色
  background-color: #e5f6ff; 
  border-radius: 10rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
  padding: 20rpx;
}

.sleep-content {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.sleep-score-container {
  display: flex;
  flex-direction: column; 
  justify-content: center;
  align-items: center;
  position: relative; // 为父元素设置相对定位
  width: 75%;
  height: 400rpx;
}

.sleep-score-bg {
  position: absolute; // 绝对定位
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1; // 让 canvas 处于最下层
}

.sleep-score-value {
  // 修改字体大小
  font-size: 48rpx; 
  font-weight: bold;
  color: black; 
}

.sleep-score-label {
  // 修改字体大小
  font-size: 30rpx; 
  margin-top: 5rpx;
  // 修改颜色为半透明黑色，降低透明度
  color: rgba(0, 0, 0, 0.5); 
}

.sleep-time-container {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.sleep-time-item {
  display: flex;
  margin-bottom: 20rpx;
  flex-direction: column;
  align-items: center;
  
}

.time-icon {
  width: 20rpx;
  height: 20rpx;
}

.time-label {
  // 修改字体大小
  font-size: 28rpx; 
  margin-bottom: 5rpx;
   // 修改颜色为半透明黑色，降低透明度
   color: rgba(0, 0, 0, 0.5); 
}

.time-value {
  // 修改字体大小
  font-size: 48rpx; 
  color: black; 
}

.step-module {
  // 为环境噪音模块添加背景色
  background-color: #f0f0f0; 
  border-radius: 10rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
  padding: 20rpx;
  padding-top: 10rpx;
}

.sleep-details-module {
  // 为环境噪音模块添加背景色
  background-color: #ccffe7; 
  border-radius: 10rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
  padding: 20rpx;
  padding-top: 10rpx;
}

// 定义动画
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.animated {
  animation-duration: 1s;
  animation-fill-mode: both;
}

.fadeIn {
  animation-name: fadeIn;
}

.divider {
  height: 2rpx;
  background-color: #d3d3d3; 
  // 添加立体效果
  box-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.2); 
  margin: 10rpx 0;
}

/* 这里可以添加组件的样式 */
.sleep-graph-container {
  position: relative;
}
.customTooltips {
  position: absolute;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 20rpx;
}
/* 图例 */
/* 睡眠趋势 */
.chart-section {
  display: flex;
  justify-content: space-around;
}
.tip-content {
  display: flex;
  justify-content: space-between;
}
.legend-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.tip-color{
  width: 30rpx;
  height: 30rpx;
  margin-right: 10rpx;
  border-radius: 6rpx;
}
.legend-color {
  width: 30rpx;
  height: 30rpx;
  margin-right: 10rpx;
  border-radius: 6rpx;
}
.n1-sleep { background-color: #83bff6; }
.n2-sleep { background-color: #00FFCC; }
.n3-sleep { background-color:  #32CD32; }
.awake { background-color: #FF0000; }
.rem-sleep { background-color: #FFFF00;}
.legend-text{
  font-size: 22rpx;
}
</style>